package org.autojs.autojs;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import net.yrom.screenrecorder.rtmp.RESFlvData;
import net.yrom.screenrecorder.rtmp.RESFlvDataCollecter;
import net.yrom.screenrecorder.task.RtmpStreamingSender;
import net.yrom.screenrecorder.task.ScreenRecorder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ScreenRecordService extends Service {

    private MediaProjectionManager mediaProjectionManager;
    private MediaProjection mediaProjection;
    private ScreenRecorder screenRecorder;
    private RtmpStreamingSender rtmpStreamingSender;
    private ExecutorService executorService;
    private AtomicBoolean isRecord = new AtomicBoolean(false);

    public static void startRecordingService(Context context) {
        Intent startIntent = new Intent(context, ScreenRecordService.class);
//        startIntent.putExtra("rtmpUrl", "rtmpUrl");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(startIntent);
        } else {
            context.startService(startIntent);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isRecord = new AtomicBoolean(false);
        mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        executorService = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String rtmpUrl = intent.getStringExtra("rtmpUrl");
        rtmpUrl = "rtmp://182.87.219.137/live/5000";
        if (rtmpUrl != null) {
            if (isRecord.get()) {
                this.stopScreenRecording();
                isRecord.set(true);
            } else {
                isRecord.set(true);
            }
            startScreenRecording(rtmpUrl);
        }
        return START_NOT_STICKY;
    }

    public void startScreenRecording(String rtmpUrl) {
        if (mediaProjectionManager != null) {
            Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
            if (captureIntent != null) {
                MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, captureIntent);
                if (mediaProjection != null) {
                    startCapture(rtmpUrl);
                }
            }
        }
    }

    private void stopScreenRecording() {
        if (screenRecorder != null) {
            screenRecorder.quit();
            screenRecorder = null;
        }
        if (rtmpStreamingSender != null) {
            rtmpStreamingSender.sendStop();
            rtmpStreamingSender.quit();
            rtmpStreamingSender = null;
        }
        if (mediaProjection != null) {
            mediaProjection.stop();
            mediaProjection = null;
        }
        isRecord.set(true);
    }


    private void startCapture(String rtmpUrl) {
        // 执行开始捕获屏幕的逻辑
        try {
            RESFlvDataCollecter collecter = (flvData, type) -> rtmpStreamingSender.sendFood(flvData, type);
            screenRecorder = new ScreenRecorder(collecter, RESFlvData.VIDEO_WIDTH, RESFlvData.VIDEO_HEIGHT, RESFlvData.VIDEO_BITRATE, 1, mediaProjection);
            executorService.execute(screenRecorder);
            rtmpStreamingSender = new RtmpStreamingSender(rtmpUrl);
            executorService.execute(rtmpStreamingSender);
        } catch (Exception e) {
            stopScreenRecording();
            isRecord.set(false);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopScreenRecording();
        if (executorService != null) {
            executorService.shutdown();
            executorService = null;
        }
    }
}
